import { init, getInstanceByDom, EChartsType } from 'echarts'
import React, { FC, useEffect } from 'react'

interface ChartProps {
  id: string
  config: any
  width?: string | number
  height?: string | number
  className?: string | undefined
}

/**
 *
 * @param id 容器元素
 * @param config ecjarts config设置
 * @param width 宽度设置
 * @param height 噶度设置
 *
 */
const Chart: FC<ChartProps> = ({ id, config, width = '200px', height = '200px', className }) => {
  let chartInstance: EChartsType | null = null

  function renderChart() {
    const renderedInstance = getInstanceByDom(document.getElementById(id) as HTMLElement)
    if (renderedInstance) {
      chartInstance = renderedInstance
    } else {
      chartInstance = init(document.getElementById(id) as HTMLElement)
    }
    chartInstance.setOption(config)
  }

  useEffect(() => {
    renderChart()
  }, [config])
  useEffect(() => {
    window.addEventListener('resize', () => chartInstance?.resize())
  }, [chartInstance])

  useEffect(() => {
    return () => {
      chartInstance && chartInstance.dispose()
    }
  }, [])

  return <div style={{ width, height }} id={id} className={className} />
}

export default Chart
